// 让小球向右下运动，遇到边缘后反弹
var ball = document.querySelector('.ball');
var ballSpeedX = 2,
  ballSpeedY = 1;
var moveCountX = 0,
  dx = 1;
var moveCountY = 0,
  dy = 1;

var rect = ball.getBoundingClientRect();
var ballWidth = rect.right - rect.left;
var ballHeight = rect.bottom - rect.top;
var startLeft = rect.left;
var startTop = rect.top;

var maxLeft = document.documentElement.clientWidth - ballWidth;
var maxTop = document.documentElement.clientHeight - ballHeight;

function moveBall() {
  var curLeft = startLeft + moveCountX * ballSpeedX;
  var curTop = startTop + moveCountY * ballSpeedY;
  if (curLeft < 0 || curLeft > maxLeft) {
    dx = -dx;
  }
  if (curTop < 0 || curTop > maxTop) {
    dy = -dy;
  }

  ball.style.left = curLeft + 'px';
  ball.style.top = curTop + 'px';
  moveCountX += dx;
  moveCountY += dy;
}

function start() {
  setInterval(() => {
    moveBall();
  }, 20);
}

star
